import {
  getAdoptInstructAccountPage,
  updateAdoptInstructAccount,
  updateAdoptInstructDescribes,
} from '@/services/api/api-cues-adopt';
import { DrawerForm, ModalForm, ProFormInstance, ProFormTextArea } from '@ant-design/pro-form';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Button, Space, Tag, message } from 'antd';
import e from 'express';
import React, { useRef, useState } from 'react';

interface DetailsArticleAdoptInstructAccountProps {
  type: number | undefined;
  articleId: string | undefined;
  onRefurbish: () => void;
}

const DetailsArticleAdoptInstructAccount: React.FC<DetailsArticleAdoptInstructAccountProps> = ({
  type,
  articleId,
  onRefurbish,
}) => {
  const actionRef = useRef<ActionType>();

  const [drawerVisit, setDrawerVisit] = useState(false);

  const [selectedAdoptInstructAccountRows, setSelectedAdoptInstructAccountRowsState] =
    useState<any[]>();

  const [selectedAdoptInstructAccountRowKeys, setSelectedAdoptInstructAccountKeysState] =
    useState<React.Key[]>();


  /**
   * 需要更新指令描述的用户列表
   */
  const [selectedAdoptUpdateInstructDescribesAccountRows, setSelectedAdoptUpdateInstructDescribesAccountRowsState] =
    useState<any[]>([]);


  return (
    <DrawerForm
      key="details_adopt_Instruct_account_drawer_form"
      title="指派收录人"
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
      }}
      trigger={
        <Button key="button_adopt_account" type="primary">
          指派收录人
        </Button>
      }
      visible={drawerVisit}
      onVisibleChange={setDrawerVisit}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <ModalForm
              key={"modal_form"}
              title="指令"
              trigger={
                <Button
                  disabled={!(selectedAdoptInstructAccountRowKeys && selectedAdoptInstructAccountRowKeys?.length > 0)}
                  key="ok"
                  type="primary"
                >
                  指令描述
                </Button>
              }
              onVisibleChange={async (visible) => {
                if (visible) {
                  setSelectedAdoptUpdateInstructDescribesAccountRowsState(selectedAdoptInstructAccountRows)

                  const response = await updateAdoptInstructAccount({
                    articleId,
                    type,
                    accounts: selectedAdoptInstructAccountRowKeys,
                  });

                  if (response.code === 0) {
                    onRefurbish();
                    message.success('提交成功');
                    actionRef.current?.reload();
                  }
                } else {
                  setSelectedAdoptUpdateInstructDescribesAccountRowsState([])
                }

              }}
              onFinish={async (values) => {

                if (selectedAdoptUpdateInstructDescribesAccountRows.length == 0) {
                  message.warning('无人员需要指令描述更新');
                  return true;
                }

                const response = await updateAdoptInstructDescribes({
                  articleId,
                  type,
                  accounts: selectedAdoptUpdateInstructDescribesAccountRows?.map(item => item.accountId),
                  ...values
                });

                if (response.code === 0) {
                  message.success('更新成功');
                  onRefurbish();
                  setDrawerVisit(false)
                  return true;
                } else {
                  return false;
                }
              }}
            >
              <div>
                以下人员会收到新的指令描述，并且覆盖之前的，如不输入则不会覆盖：
              </div>
              <Space style={{
                marginTop: '18px',
                marginBottom: '18px'
              }} size={[0, 8]} wrap>{selectedAdoptUpdateInstructDescribesAccountRows?.map(item => <Tag
                key={item.accountId}
                closable={true}
                style={{ userSelect: 'none' }}
                onClose={() => {
                  const rows = selectedAdoptUpdateInstructDescribesAccountRows.filter(row => row.accountId != item.accountId);
                  setSelectedAdoptUpdateInstructDescribesAccountRowsState(rows)
                }}
              >
                {item.accountName}
              </Tag>)}</Space>

              <ProFormTextArea
                name="instructDescribes"
                label="指令描述"
                placeholder="请输入指令描述"
              />
            </ModalForm>,
          ];
        },
      }}
      onFinish={async (values) => {
        const response = await updateAdoptInstructAccount({
          articleId,
          type,
          accounts: selectedAdoptInstructAccountRowKeys,
        });
        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <ProTable<CuesAdoptData.InstructAccountVo>
        ghost
        actionRef={actionRef}
        rowSelection={{
          selectedRowKeys: selectedAdoptInstructAccountRowKeys,
          type: 'checkbox',
          onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {

            setSelectedAdoptInstructAccountRowsState(selectedRows);

            setSelectedAdoptInstructAccountKeysState(selectedRowKeys);
          },
          getCheckboxProps: (record: CuesAdoptData.InstructAccountVo) => ({
            disabled: record.disabled === 1, // Column configuration not to be checked
          }),
        }}
        tableAlertRender={false}
        columns={[
          {
            title: '单位',
            key: 'organizationName',
            dataIndex: 'organizationName',
            hideInSearch: true,
            width: '80px',
            align: 'center',
            render: (_, record) => (
              <Tag >
                {record.organizationName}
              </Tag>
            ),
          },
          {
            title: '姓名',
            key: 'accountName',
            dataIndex: 'accountName',
            width: '100px',
            align: 'center',
          },
          {
            title: '指令人',
            key: 'instructAccountName',
            dataIndex: 'instructAccountName',
            align: 'center',
            width: '120px',
            render: (_, record) => (
              <div style={{
                textAlign: 'left',
              }}
              >
                <Space>
                  {record.isAdopt === 1 && (
                    <Tag color={record.isInstruct === 0 ? 'green' : 'orange'}>
                      {record.isInstruct === 0 ? '自主' : '指令'}
                    </Tag>
                  )}
                  {record.isInstruct === 0
                    ? record.isAdopt === 1 && <>自主收录，不可选择</>
                    : `${record.instructAccountName}`}
                </Space>
              </div>
            ),
          },
          {
            title: '收录时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            width: '150px',
            align: 'center',
            search: false,
          },
        ]}
        request={async (params = {}) => {
          const response = await getAdoptInstructAccountPage({
            articleId,
            ...params,
          });

          const rows = response.data.data.filter((item) => item.selected === 1)

          const rowIds = rows.map((item) => item.accountId);

          setSelectedAdoptInstructAccountRowsState(rows);

          setSelectedAdoptInstructAccountKeysState(rowIds);

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        rowKey="accountId"
        tableLayout="fixed"
        dateFormatter="string"
        headerTitle={false}
        bordered
        // options={{
        //   search: {
        //     name: 'name',
        //     onSearch: (keyword: string) => {
        //       return true;
        //     },
        //   },
        // }}
        search={false}
        pagination={{
          showQuickJumper: false,
          showSizeChanger: false,
          defaultPageSize: 100,
          showLessItems: false,
        }}
      />
    </DrawerForm>
  );
};
export default DetailsArticleAdoptInstructAccount;
